<template>

  <div>
    <el-dialog
      width="500px"
      :title="formData.id ? '编辑部门' : '新增部门'"
      :visible="value"
      @close="$emit('input',false)"
    >
      <el-form ref="formRef" label-width="140px" size="mini" :model="formData" :rules="rules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="2-10个字符" />
        </el-form-item>

        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formData.code" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width:100%">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :value="item.id"
              :label="item.username"
            />

          </el-select>
        </el-form-item>

        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="formData.introduce" type="textarea" placeholder="1-100个字符" style="width:100%" />
        </el-form-item>

        <el-form-item>
          <el-row justify="center" type="flex">
            <el-button type="primary" @click="onSubmit">确定</el-button>
            <el-button @click="$emit('input',false)">取消</el-button>
          </el-row>
        </el-form-item>

      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { addDapAPI, getDepartMentAPI, getDetailAPI, getMangerAPI, updateDepAPI } from '@/api/department'
export default {
  props: {
    value: Boolean,
    pid: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      formData: {
        code: '',
        introduce: '',
        managerId: '',
        name: ''

      },
      rules: {
        name: [
          // 1、给name自定义规则校验
          // 2、发送请求，获得最新数据

          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称1-10个字符', trigger: 'blur' },
          { trigger: 'blur',
            validator:
             async(rule, value, callback) => {
               let { data } = await getDepartMentAPI()
               // 编辑时部门的重复校验
               if (this.formData.id) {
                 data = data.filter(v => v.id !== this.formData.id)
               }
               const oldName = data.findIndex(v => v.name === value) >= 0
               if (oldName) {
                 callback(new Error('部门名称不能重复'))
               } else {
                 callback()
               }
             }
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码2-10个字符', trigger: 'blur' },
          { trigger: 'blur',
            validator:
             async(rule, value, callback) => {
               // 编辑时编码的重复校验
               let { data } = await getDepartMentAPI()
               if (this.formData.id) {
                 data = data.filter(v => v.code !== this.formData.code)
               }
               const oldCode = data.findIndex(v => v.code === value) >= 0
               if (oldCode) {
                 callback(new Error('部门编码不能重复'))
               } else {
                 callback()
               }
             }
          }
        ],
        managerId: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }

        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '部门介绍1-100个字符', trigger: 'blur' }

        ]
      },
      managerList: []
    }
  },
  watch: {
    value(newValue) {
      if (!newValue) {
        this.$refs.formRef.resetFields()
        this.formData = {
          code: '',
          introduce: '',
          managerId: '',
          name: ''
        }
      }
    }
  },
  async created() {
    const { data } = await getMangerAPI()
    this.managerList = data
  },

  methods: {
    // 2、定义详情方法，接收API
    async onDetail(id) {
      const res = await getDetailAPI(id)
      // 5、回填数据
      this.formData = res.data
    },
    // 在提交事件里有formData.id做判断
    async onSubmit() {
      await this.$refs.formRef.validate()
      // 调用接口
      if (this.formData.id) {
        await updateDepAPI(this.formData)
      } else {
        await addDapAPI({ ...this.formData, pid: this.pid })
      }
      // 提示用户、刷新页面
      this.$message.success(this.formData.id ? '修改成功' : '新增成功')
      // 新增成功，关闭页面
      this.$emit('input', false)
      // 刷新数据
      this.$emit('onSuccess')
    }
  }
}
</script>

<style>

</style>
